package com.tiandang.controller;

import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import tiandang.core.response.CommonReturnType;
import tiandang.core.service.FileStore;
import tiandang.core.service.WXService;
import tiandang.core.utils.Constant;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/wxQRcode")
public class QrcodeController {

  private final Logger log = LoggerFactory.getLogger(this.getClass());

  @Autowired
  private WXService wxService;

  @Autowired
  private FileStore fileStore;

//  https://developers.weixin.qq.com/miniprogram/dev/api-backend/wxacode.createQRCode.html

  @GetMapping("/getQRcode")
  public CommonReturnType getQRcode(@RequestParam(value = "managerId") String managerId) throws Exception {
    String result = null;
    String filePath = "./files/qrcode";
    String resultPath = "/files/qrcode";

    String accessToken = wxService.getAccessToken();
    String path = "pages/login/login?managerId=" + managerId;
    log.info("二维码的路径: " + path);

    Map<String, Object> param = new HashMap<>();
    param.put("access_token", accessToken);
    param.put("path", path);
    param.put("width", 300);


    JSONObject jsonObject = JSONObject.fromObject(param);

    String json = jsonObject.toString();
    String url = Constant.WECHAT_API_QRCODE + accessToken;

    // 创建Httpclient对象
    CloseableHttpClient httpClient = HttpClients.createDefault();
    // 创建Http Post请求
    HttpPost httpPost = new HttpPost(url);
    // 创建请求内容
    StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
    httpPost.setEntity(entity);
    // 执行http请求
    CloseableHttpResponse response = httpClient.execute(httpPost);
    if (response != null) {
      HttpEntity resEntity = response.getEntity();
      if (resEntity != null) {
        InputStream inputStream = resEntity.getContent();
        String imgName = new Date().getTime() + ".jpg";
        saveToImgByInputStream(inputStream, filePath, imgName);
        result = resultPath + "/" + imgName;
      }
    }
    return CommonReturnType.success(result);
  }

  public static void saveToImgByInputStream(InputStream instreams, String imgPath, String imgName)
    throws Exception {

    File file = new File(imgPath, imgName);// 可以是任何图片格式.jpg,.png等
    FileOutputStream fos = new FileOutputStream(file);
    if (instreams != null) {
      byte[] b = new byte[1024];
      int nRead = 0;
      while ((nRead = instreams.read(b)) != -1) {
        fos.write(b, 0, nRead);
      }

      fos.flush();
      fos.close();

    }
  }

}
